<?php
namespace app\cms\event;

use app\common\controller\Addon;

class Baidu extends Addon
{
    public function _initialize()
    {
        parent::_initialize();
    }
    
    public function index()
    {
        $this->assign('fields', model('cms/Baidu','loglic')->fields($this->query));
        
        $this->assign('fieldsTag', model('cms/Baidu','loglic')->fieldsTag($this->query));
        
        $this->assign('fieldsForm', model('cms/Baidu','loglic')->fieldsForm($this->formUrls()));
        
        return $this->fetch('cms@baidu/index');
	}
    
    public function push()
    {
        $this->checkApi();
        //参数
        $args = array();
        $args['cache']    = false;
        $args['field']    = 'info_id,info_parent,info_name,info_slug,info_action';
        $args['with']     = 'term,term_map';
        $args['limit']    = input('request.pageSize/d',10);
        $args['id']       = ['gt',input('request.start/d',0)];
        $args['sort']     = 'info_id';
        $args['order']    = 'asc';
        $args['status']   = 'normal';
        //查询数据
        $list = cmsSelect($args);
        if( is_null($list) ){
            $this->error(lang('cmsTipsPushFinish'),'addon/index/index?module=cms&controll=baidu&action=index');
        }
        //最后一条
        $last = end($list);
        //拼装网址
        $urls = [];
        foreach($list as $key=>$value){
            $url = $this->frontUrl($this->request->root(true).cmsUrlDetail($value));
            array_push($urls,$url);
        }
        //推送数据
        $result = json_decode($this->post($urls),true);
        if($result['error']){
            $this->error($result['message'],'addon/index/index?module=cms&controll=baidu&action=index',false,5);
        }
        //记录断点
        DcCache('cmsStart', $last['info_id'], 0);
        //跳转下一页
        if($last['info_id']){
            $this->success(lang('cmsTipsPushing').'（ID>'.$last['info_id'].'）','addon/index/index?module=cms&controll=baidu&action=push&pageSize='.$args['limit'].'&start='.$last['info_id'], false, 2);
        }else{
            DcCache('cmsStart', null);
            $this->success(lang('cmsTipsPushFinish'),'addon/index/index?module=cms&controll=baidu&action=index');
        }
	}
    
    public function tag()
    {
        $this->checkApi();
        //参数
        $args = array();
        $args['cache']    = false;
        $args['field']    = 'term_id,term_name,term_slug,term_action';
        $args['with']     = false;
        $args['limit']    = input('request.pageSize/d',10);
        $args['id']       = ['gt',input('request.startTag/d',0)];
        $args['sort']     = 'term_id';
        $args['order']    = 'asc';
        $args['status']   = 'normal';
        //查询数据
        $list = cmsTagSelect($args);
        if( is_null($list) ){
            $this->error(lang('cmsTipsPushFinish'),'addon/index/index?module=cms&controll=baidu&action=index');
        }
        //最后一条
        $last = end($list);
        //拼装网址
        $urls = [];
        foreach($list as $key=>$value){
            $url = $this->frontUrl($this->request->root(true).cmsUrlTag($value));
            array_push($urls,$url);
        }
        //推送数据
        $result = json_decode($this->post($urls),true);
        if($result['error']){
            $this->error($result['message'],'addon/index/index?module=cms&controll=baidu&action=index',false,5);
        }
        //记录断点
        DcCache('startTag', $last['term_id'], 0);
        //跳转下一页
        if($last['term_id']){
            $this->success(lang('cmsTipsPushing').'（ID>'.$last['term_id'].'）','addon/index/index?module=cms&controll=baidu&action=tag&pageSize='.$args['limit'].'&startTag='.$last['term_id'], false, 2);
        }else{
            DcCache('startTag', null);
            $this->success(lang('cmsTipsPushFinish'),'addon/index/index?module=cms&controll=baidu&action=index');
        }
	}
    
    //表单提交
    public function form()
    {
        $this->checkApi();
        //获取表单
        $urls = explode(" ",cmsTrim(input('post.urls')));
        if(!$urls){
            $this->error(lang('empty'));
        }
        //推送数据
        $result = json_decode($this->post($urls),true);
        if($result['error']){
            $this->error($result['message']);
        }
        $this->success(lang('cmsTipsPushFinish'));
    }
    
    //推送接口
    private function post($urls=[])
    {
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => config('cms.baidu_api'),
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        return curl_exec($ch);
    }
    
    //验证apiurl
    private function checkApi()
    {
        config('common.app_domain',false);
        if(!config('cms.baidu_api')){
            $this->error(lang('cmsTipsBaiduApi'),'addon/index/index?module=cms&controll=config&action=system');
        }
    }
    
    //生成前台链接
    private function frontUrl($url='')
    {
        return str_replace('/'.basename($this->request->baseFile()), '', $url);
    }
    
    //默认网页
    private function formUrls()
    {
        config('common.app_domain',false);
        $urls = [];
        $urls[0] = $this->frontUrl($this->request->root(true));
        $urls[1] = $this->frontUrl($this->request->root(true).DcUrl('cms/categorys/index'));
        $urls[2] = $this->frontUrl($this->request->root(true).DcUrl('cms/tags/index'));
        $urls[3] = $this->frontUrl($this->request->root(true).DcUrl('cms/page/news'));
        $urls[4] = $this->frontUrl($this->request->root(true).DcUrl('cms/page/top'));
        return $urls;
    }
}